<template>
  <div>
    <el-container>
      <el-header style="height: auto;">
        <el-form :inline="true" style="margin-top: 10px">
          <el-form-item label="项目" class="mt-form-item-left" style="width: 150px">
            <el-select
              v-model="project_id"
              v-loading="projectsLoading"
              style="width: 100px"
              placeholder="项目"
              filterable
              clearable
              @change="handleChangeProject"
            >
              <el-option label="所有" value="" />
              <el-option
                v-for="item in projects"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="选择网站" class="mt-form-item-left">
            <el-select v-model="select_web" placeholder="选择网站" filterable clearable>
              <el-option label="所有" value="" />
              <el-option
                v-for="item in websites"
                :key="item.id"
                :label="item.domain"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="单数" style="width: 200px">
            <el-select v-model="orders_state" clearable placeholder="状态" style="width: 120px">
              <el-option
                v-for="item in orderStateOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="过滤错误">
            <el-select v-model="include_code" clearable mul placeholder="状态">
              <el-option
                v-for="item in issueCodeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item class="mt-form-item-search">
            <el-input
              v-model="kwInput"
              placeholder="搜索关键词"
              clearable
              :autosize="{ minRows: 4}"
              @keyup.native.enter="handleGetOrders"
            />
          </el-form-item>

          <el-form-item style="width:100px;">
            <el-button type="primary" style="float: right;" @click="handleChangeWeb">搜索</el-button>
          </el-form-item>
          <el-form-item v-if="kwInput !== ''" style="width:100px;">
            <el-button type="danger" :loading="status_loading" @click="handleGetShoppingProductStatus(null)">查询状态
            </el-button>
          </el-form-item>
          <el-form-item v-if="include_code !== ''" style="width:100px;">
            <el-button type="success" :loading="sync_loading" @click="handleDeleteByIssueCode">删除所有错误产品</el-button>
          </el-form-item>
          <el-form-item style="width:100px;">
            <el-button type="info" @click="orderdetailVisual=true">订单</el-button>
          </el-form-item>
        </el-form>
      </el-header>
      <el-main>
        <el-table
          v-loading="loading"
          :data="product_datas.filter(data => !search || data.domain.toLowerCase().includes(search.toLowerCase()))"
          border
          height="700"
          :default-sort="{prop: 'orders', order: 'descending'}"
          style="width: 100%;border:2px solid black;color:black"
        >
          <el-table-column
            sortable
            prop="domain"
            width="240"
            label="domain"
          >
            <template slot-scope="scope">
              <a type="primary" :href="scope.row.link" target="_blank" title="打开产品">
                <img
                  v-if="scope.row.image !== ''"
                  :src="scope.row.image"
                  style="max-width: 80px; max-height: 80px;display: block"
                >
                <span style="display: block">{{ scope.row.domain }}</span>
              </a>
            </template>
          </el-table-column>
          <el-table-column
            sortable
            prop="link"
            width="80"
            label="产品"
          >
            <template slot-scope="scope">
              <span
                style="color: green;"
                @click="handleModifyFeed(scope.row)"
              >{{ scope.row.ps_product_id }}</span>
            </template>
          </el-table-column>
          <el-table-column
            sortable
            width="80"
            prop="orders"
            label="订单"
          >
            <template slot-scope="scope">
              <a type="primary" title="点击查看订单情况" @click="handleShowOrders(scope.row)">{{ scope.row.orders }}</a>
            </template>
          </el-table-column>
          <el-table-column
            width="120"
            prop="approvalStatus"
            label="通过状态"
          />
          <el-table-column
            prop="code"
            label="详情"
          >
            <template slot-scope="scope">
              <span style="display: block">{{ scope.row.code }}</span>
              <span>{{ scope.row.description }}</span>
              <span>{{ scope.row.detail }}</span>
            </template>
          </el-table-column>
          <el-table-column
            width="200"
            prop="lastUpdateDate"
            label="时间"
          >
            <template slot-scope="scope">
              <span style="display: block">更新:{{ scope.row.lastUpdateDate }}</span>
              <span style="display: block">处理:{{ scope.row.process_at }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="350"
          >
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="handleRemoveProductImageBg(scope.row)">去除背景</el-button>
              <el-button size="mini" type="primary" @click="handleGetShoppingProductStatus(scope.row)">查询状态</el-button>
              <el-button size="mini" title="删除" type="success" @click="handleDelete(scope.row, -2)">已处理</el-button>
              <el-button size="mini" title="删除" type="danger" @click="handleDelete(scope.row, -1)">删除</el-button>
            </template>

          </el-table-column>
        </el-table>
        <el-pagination
          v-if="product_datas.length"
          background
          class="mt-pagination"
          :current-page="page"
          :page-sizes="[10,50,100,200,300,500]"
          :page-size="pagesize"
          layout="total"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
        <el-button style="float: right" size="mini" type="primary" @click="handleDeleteAll">删除当前结果所有</el-button>

      </el-main>
      <el-dialog
        :title="feedtitle"
        :visible.sync="product_statusdialogVisible"
        width="60%"
      >
        <div>
          <json-viewer
            :value="product_status"
            :expand-depth="5"
            copyable
            boxed
            sort
          />
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="product_statusdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="product_statusdialogVisible = false">确 定</el-button>
        </span>
      </el-dialog>
      <orderdetail
        :order-static-visible="orderdetailVisual"
        :product_url="product_url"
        :website_id="current_website_id"
        :time_start="time_start"
        :time_end="time_end"
        @closeMyDialog="orderdetailVisual=false"
      />
      <feedproductmodify
        :pst-visible="feedproductVisual"
        :website_id="website_id"
        :product_id="product_id"
        :domain="domain"
        @closePstDialog="feedproductVisual=false"
      />
    </el-container>
  </div>

</template>

<script>
import { Get as GetProjects } from '@/api/erp/elicink/project'
import { Get as GetWebsite } from '@/api/erp/elicink/website'
import {
  GetShoppingBanedProducts,
  DeleteShoppingBanedProducts,
  SyncShoppingBanedProducts,
  GetShoppingproductstatus,
  RemovePrestashopImagesBg
} from '@/api/orders/shoppingproductsapi'
import orderdetail from '@/views/orders/element/orderdetail'
import qs from 'qs'
import JsonViewer from 'vue-json-viewer'

import Cookies from 'js-cookie'
import feedproductmodify from '@/views/orders/element/feedproductmodify'

export function getToken(key) {
  const v = Cookies.get(key)
  return v && parseInt(v) || null
}

export function setToken(key, value) {
  return Cookies.set(key, value, { expires: 30 })
}

const ProjectKey = 'orders_project_id'
export default {
  name: 'Banedproducts',
  components: {
    feedproductmodify,
    orderdetail,
    JsonViewer
  },
  data() {
    return {
      orderStateOptions: [
        { 'value': 1, 'label': '有出单' },
        { 'value': 0, 'label': '没出单' },
        { 'value': -1, 'label': '未查询' },
        { 'value': -2, 'label': '已处理' }
      ],
      include_code: '',
      issueCodeOptions: [
        { 'value': 'preemptive_item_disapproval_promotext_and_watermark_images', 'label': '图片有水印' },
        { 'value': 'image_unwanted_overlays', 'label': '图片包含促销信息' },
        { 'value': 'landing_page_error', 'label': '落地页错误' },
        { 'value': 'mobile_landing_page_error', 'label': '手机打不开' },
        { 'value': 'price_mismatch', 'label': '价格不匹配' },
        { 'value': 'image_too_small', 'label': '图片太小' },
        {
          'value': 'preemptive_item_disapproval_price_untrusted',
          'label': 'preemptive_item_disapproval_price_untrusted'
        },
        { 'value': 'policy_violation', 'label': '违反广告政策' }
      ],
      modify_website_id: '',
      modify_website_domain: '',
      modifyWebsiteVisuable: false,
      landing_website_domain: '',
      landing_website_id: '',
      showLandingPage: false,
      googleAdsStaticVisuable: false,
      current_ads_id: '',
      feedproductVisual: false,
      googleReportConfigVisual: false,
      adsmanagerperformancedata: [],
      showperformanceHistory: false,
      remoteModifydialogVisible: false,
      currentOpRow: {
        'id': 0,
        'name': '',
        'price': '',
        'description': '',
        'long_description': '',
        'meta_title': '',
        'meta_description': '',
        'meta_keywords': '',
        'web__domain': '',
        'product_id': ''
      },
      search: '',
      show_performance: false,
      merchant_website_id: '',
      merchantVisible: false,
      orderdetailVisual: false,
      product_url: '',
      adwordsrechargesVisuable: false,
      adwordsModifyNoteVisuable: false,
      total_sales: 0,
      total_cost: 0,
      total_orders: 0,
      order_sales: 0,
      daily_sales: 0,
      orderStaticVisible: false,
      loading: false,
      time_start: '',
      time_end: '',
      current_website_id: '',
      current_website_domain: '',
      projects: [],
      project_id: null,
      projectsLoading: false,
      timerange: '',
      select_web: '',
      orders_state: 1,
      kwInput: '',
      order_by: 'create_at',
      order_desc: 1,
      // pagination
      pagesize: 100,
      fileList: [],
      base_api: '',
      filter: {},
      page: 1,
      total: 0,
      websites: [],
      product_datas: [],
      website_id: '',
      product_id: '',
      domain: '',
      sync_loading: false,
      status_loading: false,
      product_statusdialogVisible: false,
      product_status: '',
      feedtitle: '产品feed状态'
    }
  },
  created() {
    this.project_id = getToken(ProjectKey)
    this.handleFetchProjects()
    this.handleGetWebsite()
    this.base_api = process.env.VUE_APP_BASE_API + '/orders/api/orders_api_staticsbywebsite/'
  },
  methods: {
    handleSyncAliyun() {
      this.sync_loading = true
      SyncShoppingBanedProducts('', qs.stringify({
        website_id: this.select_web
      }))
        .then(response => {
          this.sync_loading = false
          this.$notify({
            title: '成功',
            message: '提交成功，后台需要时间处理',
            type: 'success',
            duration: 2000
          })
        })
        .catch(e => {
          this.sync_loading = false
          console.log('some error')
        })
    },
    handleDeleteByIssueCode() {
      DeleteShoppingBanedProducts('', qs.stringify({
        select_web: this.select_web,
        include_code: this.include_code,
        delete_code: -1,
        orders: this.orders_state
      }))
        .then(response => {
          this.$notify({
            title: '成功',
            message: '删除错误状态:' + this.include_code + '成功',
            type: 'success',
            duration: 500
          })
        })
        .catch(e => {
          console.log('some error')
        })
    },
    handleDeleteAll() {
      if (this.include_code === '') {
        return
      }
      const msg = '你确定要删除所有吗' + this.product_datas.length + '？删除数据后无法再查询'
      if (confirm(msg) === false) {
        return
      }
      this.product_datas.forEach(item => {
        DeleteShoppingBanedProducts('', qs.stringify({
          merchant_id: item.merchant_id,
          product_id: item.product_id,
          delete_code: -1
        }))
          .then(response => {
            this.$notify({
              title: '成功',
              message: '产品:' + item.product_id + '提交成功',
              type: 'success',
              duration: 500
            })
            console.log('delete product ' + item.product_id)
          })
          .catch(e => {
            console.log('some error')
          })
      })
      this.getList()
    },
    handleDelete(row, value) {
      if (value === -1) {
        if (confirm('你确定要删除吗？删除数据后无法再查询') === false) {
          return
        }
      }
      DeleteShoppingBanedProducts('', qs.stringify({
        merchant_id: row.merchant_id,
        product_id: row.product_id,
        delete_code: value
      }))
        .then(response => {
          this.$notify({
            title: '成功',
            message: '产品:' + row.product_id + '提交成功',
            type: 'success',
            duration: 2000
          })
          this.product_datas.forEach((v, i) => {
            if (row.product_id === v.product_id && row.merchant_id === v.merchant_id) {
              this.product_datas.splice(i, 1)
            }
          })
        })
        .catch(e => {
          console.log('some error')
        })
    },
    handleRemoveProductImageBg(row) {
      // this.status_loading = true
      let website_id = this.select_web
      let product_id = this.kwInput
      if (row !== null) {
        website_id = row.website_id
        product_id = row.ps_product_id
      }
      RemovePrestashopImagesBg('', qs.stringify({
        website_id: website_id,
        product_id: product_id
      }))
        .then(response => {
          console.log(response)
        })
        .catch(e => {
          this.status_loading = false
          console.log('some error')
        })
    },
    handleGetShoppingProductStatus(row) {
      // this.status_loading = true
      let website_id = this.select_web
      let product_id = this.kwInput
      if (row !== null) {
        website_id = row.website_id
        product_id = row.ps_product_id
        this.feedtitle = '网站:' + row.domain + '产品:' + row.ps_product_id + ' Feed状态'
      } else {
        this.status_loading = true
        this.feedtitle = '网站:' + website_id + '产品:' + product_id + ' Feed状态'
        console.log(website_id, product_id)
      }
      this.loading = true
      GetShoppingproductstatus('', qs.stringify({
        website_id: website_id,
        product_id: product_id
      }))
        .then(response => {
          this.loading = false
          this.status_loading = false
          this.product_status = response.data
          this.product_statusdialogVisible = true
        })
        .catch(e => {
          this.status_loading = false
          this.loading = false
          console.log('some error')
        })
    },
    handleModifyFeed(row) {
      this.website_id = row.website_id
      this.product_id = row.ps_product_id
      this.domain = row.domain
      this.feedproductVisual = true
    },
    handleGetWebsiteStateLabel(val) {
      for (let i = 0; i < this.orderStateOptions.length; i++) {
        if (this.orderStateOptions[i].value === val) {
          return this.orderStateOptions[i].label
        }
      }
      return val
    },
    handleShowModifyWebsite(row) {
      this.modifyWebsiteVisuable = true
      console.log('hhfdsfdsf')
      this.modify_website_id = row.website_id
      this.modify_website_domain = row.domain
    },
    handleShowLandingPage(row) {
      this.landing_website_id = row.website_id
      this.landing_website_domain = row.domain
      this.showLandingPage = true
    },
    handleShowAdsChat(row) {
      this.current_ads_id = row.ads_id
      this.googleAdsStaticVisuable = true
    },
    getList() {
      this.loading = true
      this.show_performance = false
      GetShoppingBanedProducts(this.website_id, qs.stringify({
        project_id: this.project_id,
        orders: this.orders_state,
        kw: this.kwInput,
        include_code: this.include_code,
        website_id: this.select_web,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by
      }))
        .then(response => {
          this.product_datas = response.data
          this.total = response.total
          this.loading = false
        }).catch(err => {
          console.log(err)
          this.loading = false
        })
    },
    handleFetchProjects() {
      this.projectsLoading = true
      GetProjects()
        .then(response => {
          this.projectsLoading = false
          this.projects = response.data.data
          if (this.projects.length) {
            this.project_id = getToken(ProjectKey) || null
          }
        })
        .catch(e => {
          this.projectsLoading = false
        })
    },
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    handleShowOrders(row) {
      this.current_website_id = row.website_id
      this.orderdetailVisual = true
    },
    handleGetWebsite() {
      GetWebsite(null, qs.stringify({ 'project_id': this.project_id })).then(response => {
        this.websites = response.data.data
      })
    },
    handleChangeProject() {
      setToken(ProjectKey, this.project_id)
      this.handleGetWebsite()
    },
    handleChangeWeb() {
      this.page = 1
      this.search = ''
      this.getList()
    }
  }
}
</script>

<style scoped>
  .app-container >>> table, tr {
    border-color: black;
  }

  .el-header {
    height: 120px;
  }

  .el-header, .el-footer {
    background-color: #00c0ef;
    color: white;
  }

  .el-container >>> .pointer {
    cursor: pointer;
    color: #409EFF;
  }

  .el-container >>> a:visited {
    color: purple;
  }

  .el-container >>> a:link {
    color: #409EFF;
  }

  .el-container >>> a:active {
    color: red;
  }
</style>
